<?php

namespace app\api\controller;

use app\admin\model\Admin;
use app\admin\model\Batch;
use app\admin\model\Group;
use app\admin\model\m\Apply;
use app\admin\model\m\Info;
use app\admin\model\Material;
use app\admin\model\Mcategory;
use app\common\controller\Api;
use think\Config;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\controller\Backend;
use think\Session;

/**
 *  物品 领用
 */
class Goods extends Api
{
    /**
     * 前台提交过来,需要排除的字段数据
     */
    protected $excludeFields = [];      // demo: ['info_data','group_id'];
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    //  3.1     领用物料时, 记录领取金额, 这个单价从哪获取?    0215 - 02.20



    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (array_key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else if (array_key_exists($this->excludeFields, $params)) {
            unset($params[$this->excludeFields]);
        }
        return $params;
    }

    public function demo(){
        echo '管理员id是: ' . $this->auth->id ;
        echo '物品领用初始化';
    }

    // 查看我的物品领用
    // 关联大类: 饲料,药品,耗材,设备
    public function index(){
        // DEMO:  获取admin信息, 主要用于获取所属厂区id !
        $aa = Admin::get(intval($this->auth->id));      // print_r( $aa ); die;

        $model = new Apply();
        $filter = $this->request->post();
        // 按筛选条件查询~
        //   TODO 状态筛选
        $param = [];
        //  $filter['material_id'] =   1, 2, 4, 7
        $param['mi.mmaterial_id'] = $filter['material_id'];     // $filter['material_id'] =   1, 2, 4, 7
        //  ['全部', '已通过', '待审核', '已驳回'],
        if( $filter['statusVal'] != "全部"){
            $param['a.status'] = $filter['statusVal'];      // $filter['statusVal'] =  ['全部', '已通过', '待审核', '已驳回'],
        }
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        $data['list'] = $model->alias("a")
            ->join("m_info mi", "mi.id = a.info_id" ,"left")
            ->where($param)
            ->where("a.deletetime", null)
            ->field("a.id,a.group_id,a.batch_id,a.info_id,a.num,a.apply_id,a.status,a.comment,a.createtime,a.updatetime,a.deletetime ")
            ->order(['a.createtime'=>'desc'])
            ->select();
//echo Db::getLastSql(); die;
        foreach($data['list'] as &$val){
            $val['group'] = $val['group_id'] ? Group::get($val['group_id'])->toArray() : [];       //   可改写为关联查询
            $val['batch'] = $val['batch_id'] ? Batch::get($val['batch_id'])->toArray() : [];       //
            $val['info'] = $val['info_id'] ? Info::get($val['info_id'])->toArray() : [];           //

        }

        $this->success('成功', $data);
    }
    public function add(){
        $this->model = new Apply();

        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post();
        if (empty($params)) {
            $this->error('不能提交空数据');
        }
        $params = $this->preExcludeFields($params);
        // 校正提交数据
        $params['admin_id'] = $this->auth->id;
        $params['info_data'] = json_encode($params['info_data'], JSON_UNESCAPED_UNICODE);
        $params['batch_id'] = $params['batch_id']>0 ? $params['batch_id'] : null ;

        # 领用库存判断,  建议是设置成可以领用负数
        # 需要在审批位置设置
        # TODO 19

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证      TODO:  为api增加模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("数据未提交");
        }
        $this->success("申请成功,等待审核");
    }


    /**
     * 类型-品类-物料
     * @return data
     */
    public function goodsdata(){
        $mmaterial_id = intval($this->request->get('material_id'));
        $info = new Info();
        $mcategory = new Mcategory();
        $material = new Material();

        //物料查询   todo
        // 按品类分类
        $cate_info = $mcategory->where("status",1)->field("id as value, name as text")->select();
        $cate_info = array_column($cate_info, null, "value");
        foreach($cate_info as &$item){
            $item['child'] = $info
                ->where("status",1)
                ->where("mcategory_id", $item['value'])
                ->field("id as value, name as text, code, depot_id, mmaterial_id, mafactory_id, mcategory_id, specs, unit, comment, name, merge_name, status")
                ->order(['weigh'=>'desc','createtime'=>'desc'])
                ->select();
        }
        $data['info']= $cate_info;

        // 类型-品类
        $materials = $material->where("status",1)->field("id as value, name as text")->select();
        $materials = array_column($materials, null, "value");
        foreach($materials as &$item){
            $item['child'] = $mcategory
                ->where("status",1)
                ->where("material_id",$item['value'])
                ->field("id as value, name as text, material_id")
                ->order(['weigh'=>'desc','createtime'=>'desc'])
                ->select();
        }
        $data['mcategory']  = $materials ;

        $this->success('成功', $data);
    }


    public function edit(){
        // 修改已提交的表单: 审核通过以外的状态:重新审核
        //
        // TODO:  修改表单重新审核,  无人审核前直接修改,   已通过的表单不可修改
        $model = new Apply();
        $ids = $this->request->get("id");
        // TODO:  员工看到自己的信息,  审批权限可看到所有信息
        if( 1 ){
            //  DEMO:  if  $this->auth->hasAuth ( approve )
            $param['a.admin_id'] = $this->auth->id ;
        }

        $param['a.id'] = $ids ;
        // TODO:
        $data = $model->alias("a")
            ->where($param)
            ->join("batch b", "b.id = a.batch_id" ,"left")
            ->field("a.*")
            ->order(['a.createtime'=>'desc'])
            ->with(['batch','group'])
            ->find();

//        print_r($data['info_data']); die;

        if (false === $this->request->isPost()) {
            $this->success("", $data, $data ? 200 : 201);
        }

        // post  提交修改
        $params = $this->request->post();
        print_r($params);die;
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            //            if ($this->modelValidate) {
            //                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
            //                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
            //                $row->validateFailException()->validate($validate);
            //            }
            $result = $data->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    public function del(){
        // 删除已提交的表单:  仅限未审核通过
        $ids = $this->request->post("id");
        // TODO:  操作员可以直接删除, 管理员会收到提醒, 查看哪些被删除, 或增加删除原因,  管理员可恢复记录

        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    // 获取单条记录, 包括相关信息, 审批信息.
    public function detail(){
//        $ids = $this->request->post("id");
//        $row = $this->model->get($ids);
//        if (!$row) {
//            $this->error(__('No Results were found'));
//        }
//        $adminIds = $this->getDataLimitAdminIds();
//        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
//            $this->error(__('You have no permission'));
//        }
//
//        $this->view->assign('row', $row);
//        return $this->view->fetch();
    }


    // 物料库存查询
    public function getstock(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }
        $factory_id = $this->auth->factory_id;

        $res = Db::name("m_stockbill")
            ->field("*, sum(cal_num) as sum_num ")
            ->where("factory_id", $factory_id )
            ->where("info_id", $filter['id'] )
            ->where("status", "已通过" )
            ->where("deletetime", null )
            ->group("info_id")
            ->select();

        $this->success('成功', $res);
    }

    // 领用单查询
    public function getdata(){
        $filter = $this->request->get();
        if( !isset($filter['id']) || !$filter['id'] ){
            $this->success('无参数输入', '');
        }
        $factory_id = $this->auth->factory_id;

        $res = Db::name("m_apply")
            //->where("admin_id", $factory_id )
            ->where("id", $filter['id'] )
            ->find();

        $this->success('成功', $res);
    }


}